<?php
   class Model_Places {
      
      public function add($data) {
         $title = $data['title'];
         $location = $data['location'];
         $lat = $data['lat'];
         $lng = $data['lng'];
         // NOW WE ALWAYS CREATE A NEW RECORD!
         // if not in the table yet, add new location and return its id
//         $isExistent = $this->getLocationByCoordinates($lat, $lng);
//         if ($isExistent) {
//            // use existent place data
//            return $isExistent['id'];
//         } else {
            // insert new record in table
        $dbTable = new Model_DbTable_Places();
        $newLocationData = array('title'     => $title,
                                'user_id'    => $data['user_id'],
                                'location'   => serialize(explode(',', $location)),
                                'latitude'   => $lat,
                                'longitude'  => $lng,
                                'icon_path'  => '',
                                'description'=> '',
        );
        $insertResult = $dbTable->insert($newLocationData);
        return ($insertResult) ? $insertResult : 0;
//         }
      }
      
      public function save($data, $where) {
         $model = new Model_DbTable_Places();
         $result = $model->update($data, $where);
         return $result;
      }
      
      public function delete() {
         
      }
      
      public function getLocationByCoordinates($lat, $lng) {
         $model = new Model_DbTable_Places();
         $where['latitude  = ?'] = $lat;
         $where['longitude = ?'] = $lng;
         $placeDataObject = $model->fetchRow($where);
         return $placeDataObject;
      }
      
      public function getLocationByUserId($userId) {
         $userModel = new Model_Users();
         $usersData = $userModel->getByUserId($userId);

         $whereParams = array('id' => $usersData['location']);
         $placeData = $this->getByCertainField($whereParams);
         return array('lat' => $placeData['latitude'], 'lng' => $placeData['longitude']);
      }
   /**
    * @todo refactor all fetches to use this function(see getByPlaceAndUserId).
    * @param array $params Keys are fields and Values are values. If null, then retrieve all places.
    * @return type 
    */
   public function getByCertainField($whereParams = null) {

      $model = new Model_DbTable_Places();
      if (!is_null($whereParams)) {
        foreach ($whereParams as $fieldName => $value) {
            $where[$fieldName] = $value;
        }
         $placeDataObject = $model->fetchRow($where);
         $location = unserialize($placeDataObject->location);
         $placeData = array(
                'id'        => $placeDataObject->id,
                'title'     => $placeDataObject->title,
                'location'  => implode(', ', $location),
                'latitude'  => $placeDataObject->latitude,
                'longitude' => $placeDataObject->longitude,
                //'image'   => $userDataObject->image ? $userDataObject->image : '',
        );
      } else {
         $placeData = $this->getAllPlaces();
      }
         return $placeData;
    }
      
      public function getAllPlaces() {
         $model = new Model_DbTable_Places();
         $placeDataObject = $model->fetchAll();
         foreach ($placeDataObject as $place) {
            // $address = unserialize($place['location']);
            $lat[] = $place['latitude'] ;
            $lng[] = $place['longitude'];
         }
         return array('latitude' =>$lat, 'longitude' => $lng);
      }

      /* xml template
       *<markers>
           <marker>
             <name>VODAFONE</name>
             <address>near Ghumaghumalu Restaurant, Marripalem, Visakhapatnam</address>
             <lat>17.74033553</lat>
             <lng>83.25067267</lng>
           </marker>
        </markers>
       */
      // @todo maybe show home place for the owner?
      public function getAllPlacesInXML($id = null) {
         $userModel = new Model_Users();
         $usersIds = $userModel->getPublicPlacesOwnerIds();
         // Show currently logged user his/her places independently from privacy settings.
         if (!is_null($id)) {
             $usersIds[] = array('id' => $id);
         }

         // Show all public places but home locations for security purposes.
         if (count($usersIds) > 1) {
            foreach ($usersIds as $key => $userId) {
                if (isset($where)) {
                    $where .= ' OR (user_id = '.$userId['id']. ')';
                } else {
                    $where = '(user_id = '.$userId['id'].')';
                }
            }

         $model = new Model_DbTable_Places();
         $placeDataObject = $model->fetchAll($where);
         header("Content-Type: xml");
         // create a new XML document
         $doc = new DomDocument('1.0');
         // add root node
         $markers = $doc->appendChild($doc->createElement('markers'));

         foreach ($placeDataObject as $place) {
            $locationArray = unserialize($place->location);
            $locationString = implode(', ', $locationArray);
            $marker  = $markers->appendChild($doc->createElement('marker'));
            $marker->appendChild($doc->createElement('name', $place->title));
            $marker->appendChild($doc->createElement('address', $locationString));
            $marker->appendChild($doc->createElement('lat',     $place->latitude));
            $marker->appendChild($doc->createElement('lng',     $place->longitude));
         }
         //$doc->save(APPLICATION_PATH."/../public/markers.xml");
         return $doc->saveXML($doc);
         }
      }
      
      public function getPaginatorRows ($userId, $pageNumber = 1) {
         $model = new Model_DbTable_Places();
         $select = $model->select();
         $select->where('user_id =? ', $userId)
                ->order('title');
         $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
         $paginator->setCurrentPageNumber($pageNumber);
         $paginator->setItemCountPerPage(10);
         $paginator->setPageRange(1);
         return $paginator;
      }
//      
//      public function getByPlaceId($placeId) {
//         $model = new Model_DbTable_Places();
//         $where['id=?'] = $placeId;
//         $placeDataObject = $model->fetchRow($where);
//         $location = unserialize($placeDataObject->location);
//         $placeData = array(
//            'id'      => $placeDataObject->id,
//            'title'   => $placeDataObject->title,
//            'location'=> implode(', ', $location),
//            //'image'   => $userDataObject->image ? $userDataObject->image : '',
//         );
//         return $placeData;
//      }

   public function getByPlaceAndUserId($placeId, $userId = null) {

      $model = new Model_DbTable_Places();
      $where['id'] = $placeId;
      if (!is_null($userId)) {
         $where['user_id'] = $userId;
      }

      $placeDataObject = $model->fetchRow($where);

      $location = unserialize($placeDataObject->location);
      $placeData = array(
            'id'        => $placeDataObject->id,
            'title'     => $placeDataObject->title,
            'location'  => implode(', ', $location),
            'latitude'  => $placeDataObject->latitude,
            'longitude' => $placeDataObject->longitude,
            //'image'   => $userDataObject->image ? $userDataObject->image : '',
       );

         return $placeData;
    }

   }